package com.icezzz.upload;

import java.io.File;
import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/")
public class UploadController {
	public static final String path = "C:/upload";
	// http://127.0.0.1:8080/upload
	@RequestMapping(value = "/upload", method = RequestMethod.GET, produces = "text/html")
	public String uplaod() {
		return code();
	}

	// http://127.0.0.1:8080/upload
	@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html")
	public String uplaodPost(@RequestParam("file") MultipartFile file) {
		String originalFilename = file.getOriginalFilename();
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		File fileSave = new File(path + "/" + originalFilename);
		try {
			file.transferTo(fileSave);
			return code();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return error();
	}
	
	public String code() {
		String str = ""
		         + "<htmL>"
				 + "  <head>"
				 + "    <meta http-equiv = \"Content-type\" content = \"text/html;charset=UTF-8\"/>"
				 + "    <meta http-equiv = \"X-UA-Compatiable\" content = \"IE=edge,chrome=1\"/>"
				 + "    <title>文件上传</title>"
				 + "  </head>"
				 + "  <body>"
				 + "    <div>"
				 + "      <form method=\"post\" action = \"/upload\" enctype = \"multipart/form-data\">"
				 + "        <input id = \"file\" name= \"file\" type = \"file\"/>"
				 + "        <input id = \"submit\" name= \"上传\" type = \"submit\"/>"
				 + "      </form>"
				 + "    </div>"
				 + "  </body>"
				 + "</html>";
		 return str;
	}
	
	public String error() {
		String str = ""
				+ "<htmL>"
				+ "  <head>"
				+ "    <meta http-equiv = \"Content-type\" content = \"text/html;charset=UTF-8\"/>"
				+ "    <meta http-equiv = \"X-UA-Compatiable\" content = \"IE=edge,chrome=1\"/>"
				+ "    <title>错误</title>"
				+ "  </head>"
				+ "  <body>"
				+ "    <div>上传失败</div>"
				+ "    </div>"
				+ "  </body>"
				+ "</html>";
		return str;
	}
}
